<template>
  <view class="info">
    <form>
      <view class="avatar">
        <image @click="avatarChange" @load="hideLoading" :src="avatarUrl" mode=""></image>
      </view>
      <view class="nickname item_info">
        <view class="text">用户昵称:</view>
        <input class="nickname-text" type="text" v-model="userInfo.nickname" v-if="isMy">
        <view v-else class="nickname-text">{{ userInfo.nickname }}</view>
      </view>
      <view class="gender item_info">
        <view class="text">性别:</view>
        <select v-if="isMy" v-model="userInfo.gender">
          <option value="男">男</option>
          <option value="女">女</option>
          <option value="保密">保密</option>
        </select>
        <view v-else class="nickname-text">{{ userInfo.gender == '' ? "保密" : userInfo.gender }}</view>
      </view>
      <view class="email item_info">
        <view class="text">邮箱:</view>
        <input placeholder="请输入邮箱" class="nickname-text" type="email" v-model="userInfo.email" v-if="isMy">
        <view v-else class="nickname-text">{{ userInfo.email == '' ? "暂无信息" : userInfo.email }}</view>
      </view>
      <view class="birthday item_info">
        <view class="text">生日:</view>
        <input class="nickname-text" type="date" v-model="userInfo.birthday" v-if="isMy">
        <view v-else class="nickname-text">{{ userInfo.birthday == '' ? "暂无信息" : userInfo.birthday }}</view>
      </view>
      <view class="phone item_info">
        <view class="text">手机号码:</view>
        <input v-if="isMy" placeholder="请输入手机号码" class="nickname-text" type='number' v-model="userInfo.phone">
        <view v-else class="nickname-text">{{ userInfo.phone == '' ? "暂无信息" : userInfo.phone }}</view>
      </view>
      <view class="introduce">
        <view class="text">个人简介:</view>
        <textarea class="textarea nickname-text" v-if="isMy" maxlength="160" placeholder="请输入个人简介" @blur="blurHandler"
          type='number' :value="introduce">

        </textarea>
        <view class="textarea" v-else>{{ userInfo.introduce == '' ? '这个人很奇怪，什么都没有说。' : userInfo.introduce }}</view>
      </view>
      <button v-if="isMy" class="submit" @click="submit">完成修改</button>
    </form>
    <view class="edit-avatar" :class="isShow ? 'show' : 'hide'">
      <view class="close iconfont  icon-fenxiang " @click="closeImg"></view>
      <view class="finish iconfont  icon-duihao" @click="cropImage"></view>
      <img ref="image" :src="imageSrc" style="width: 100%;" />
    </view>
  </view>
</template>

<script setup>
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
import { onLoad, onReady, } from '@dcloudio/uni-app';
import { useUserStore } from '../../store/modules/user'
import { reactive, ref, onMounted, nextTick, onBeforeUnmount } from 'vue';
import { getUserInformation, uploadFile, uploadIfonmation } from "../../api/info.js"
import { FG } from "../../api/req.js"
let user = useUserStore()
let isMy = ref(false)
let userInfo = reactive({})
let isShow = ref(false)

const imageSrc = ref('');
const image = ref(null);
let cropper = null;
let avatarUrl = ref('')
let introduce = ref('')
let backintroduce = ''
function isBinaryTemporaryUrl(url) {
  return url.startsWith('blob:');
}
function isValidEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}
function isValidPhoneNumber(phoneNumber) {
  const phoneRegex = /^\+?\d{1,3}?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}$/;
  return phoneRegex.test(phoneNumber);
}
function isValidChineseEnglishString(str) {
  const chineseEnglishRegex = /^[\u4e00-\u9fa5A-Za-z0-9]{4,16}$/;
  return chineseEnglishRegex.test(str);
}

// 将二进制临时url转换为file对象的 Promise 的函数
function convertBinaryUrlToFile(binaryUrl) {
  return fetch(binaryUrl)
    .then(response => response.blob()) // 获取 Blob 对象
    .then(blob => {
      const file = new File([blob], 'FGavatar.jpg', { type: blob.type });
      return file;
    })
    .catch(error => {
      throw error;
    });
}

async function submit(e) {
  uni.showLoading({})
  if (isBinaryTemporaryUrl(avatarUrl.value)) {
    let file = await convertBinaryUrlToFile(avatarUrl.value)
    let res = await uploadFile({
      file: file,
    })
    if (res.status == 200) {
      userInfo.img = res.fileUrl.split('/').slice(1).join('/')
    }
  }
  userInfo.introduce = backintroduce
  if (!(isValidChineseEnglishString(userInfo.nickname))) {
    uni.showToast({
      title: '用户名称格式不正确',
      icon: 'none',
      mask: true,
      duration: 500,
    })
    return
  }
  if (!(isValidEmail(userInfo.email) || userInfo.email == '')) {
    uni.showToast({
      title: '邮箱格式不正确',
      icon: 'none',
      mask: true,
      duration: 500,
    })
    return
  }

  if (!(isValidPhoneNumber(userInfo.phone) || userInfo.phone == '')) {
    uni.showToast({
      title: '手机号码格式不正确',
      icon: 'none',
      mask: true,
      duration: 500,
    })
    return
  }
  console.log(userInfo);
  let res = await uploadIfonmation({
    data: {
      id: userInfo._id,
      phone: userInfo.phone,
      email: userInfo.email,
      nickname: userInfo.nickname,
      gender: userInfo.gender,
      birthday: userInfo.birthday,
      img: userInfo.img,
      introduce: userInfo.introduce,
    }
  })
  if (res.status == 200) {
    uni.hideLoading()
    uni.setStorageSync('user', userInfo)
    uni.showToast({
      title: '修改成功',
      icon: 'success',
      mask: true,
      duration: 1000,
    })
  }
}
function blurHandler(e) {
  backintroduce = e.detail.value
}
function avatarChange() {
  let itemList = ['预览头像', '从相册选择']
  if (!isMy.value) {
    itemList = ['预览头像']
  }
  uni.showActionSheet({
    itemList,
    success: (res) => {
      switch (res.tapIndex) {
        case 0:
          uni.previewImage({
            urls: [avatarUrl.value],
          })
          break
        case 1:
          chooseAndCrop()
          break
      }
    },
  })
}
function hideLoading() {
  nextTick(() => {
    uni.hideLoading()
  })
}
onLoad(async (param) => {
  if (!user.user) {
    let data = uni.getStorageSync('user')
    user.user = data
  }
  if (param.id == undefined) {
    return uni.switchTab({
      url: '/pages/chatList/chatList'
    })
  }
  if (param.id == user.user._id) {
    isMy.value = true
  }
  uni.setNavigationBarTitle({
    title: '个人资料',
  })
  if (!isMy.value) {
    try {
      uni.showLoading({
        mask: true,
      })
      let { data } = await getUserInformation({ id: param.id })
      for (let key in data) {
        userInfo[key] = data[key]
      }
    } catch (err) {
      console.log(err);
    }
  } else {
    userInfo = user.user
  }
  avatarUrl.value = `${FG.baseUrl}/static/${userInfo.img}`
  if (userInfo.gender == '') {
    userInfo.gender = '保密'
  }
  introduce.value = userInfo.introduce
  backintroduce = userInfo.introduce
  console.log(introduce.value, typeof (introduce.value));
})
function dataURLtoFile(dataUrl, filename) {
  let arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}
function closeImg() {
  isShow.value = false
}
const chooseAndCrop = async () => {
  const { tempFilePaths } = await uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
  });
  imageSrc.value = tempFilePaths[0];
  isShow.value = true
  nextTick(() => {
    initCropper();
  });
};

const initCropper = () => {
  if (cropper) {
    cropper.destroy();
  }
  cropper = new Cropper(image.value, {
    aspectRatio: 1, // 宽高比
    viewMode: 1, // 视图模式
    // 其他配置项...
    dragMode: 'move',
    cropBoxResizable: false,
    cropBoxStyle: {
      border: '1px dashed #000', // 设置虚线边框样式
      'border-radius': '50%', // 设置圆形裁剪框
      backgroundColor: '#fff' // 设置裁剪框背景颜色
    }
  });
};

onMounted(() => {
  if (imageSrc.value) {
    initCropper();
  }
});

// 裁剪图片
const cropImage = async () => {
  const canvas = cropper.getCroppedCanvas();
  let croppedImage = canvas.toDataURL('image/jpeg');
  let file = dataURLtoFile(croppedImage, 'FGavatar.jpg')
  let url = URL.createObjectURL(file)
  avatarUrl.value = url
  closeImg()
};

// 组件销毁前清理
onBeforeUnmount(() => {
  if (cropper) {
    cropper.destroy();
  }
});
</script>

<style lang="scss" scoped>
.info {
  width: 100%;
  height: calc(100vh - 44px - env(safe-area-inset-top));
  padding: 30rpx;
  position: relative;

  .avatar {
    display: block;
    width: 100%;
    text-align: center;


    image {
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
      overflow: hidden;
    }
  }

  .item_info {
    display: flex;
    align-items: center;
    height: 60rpx;
    margin: 20rpx 0;

    .text {
      font-size: 30rpx;
      margin-right: 30rpx;
    }

    .nickname-text {
      width: max-content;
      line-height: 60rpx;
    }
  }

  .introduce {
    margin-bottom: 30rpx;

    .textarea {
      margin: 20rpx auto;
      background-color: #eee;
      border-radius: 20rpx;
      padding: 10rpx;
      min-height: 300rpx;
    }
  }

  .submit {}

  .edit-avatar {
    width: 100%;
    height: calc(100vh - 44px - env(safe-area-inset-top));
    position: absolute;
    top: 0;
    left: 0;
    z-index: 800;
    background-color: #07070770;



    .iconfont {
      position: absolute;
      font-size: 50rpx;
      color: antiquewhite;
      z-index: 99999999999;
    }

    .close {
      top: 20rpx;
      left: 20rpx;
    }

    .finish {
      top: 20rpx;
      right: 20rpx;
    }

  }

  .show {
    display: block;
  }

  .hide {
    display: none;
  }
}
</style>